from datetime import datetime, timedelta

from dulwich.porcelain import status
from tortoise.expressions import Q

from app.core.crud import CRUDBase
from app.models import AppointmentLock, OrdersList
from app.models.appointment import AppointmentList
from app.schemas.appointment import AppointmentListCreate, AppointmentListUpdate


class AppointmentListController(CRUDBase[AppointmentList, AppointmentListCreate, AppointmentListUpdate]):
    def __init__(self):
        super().__init__(model=AppointmentList)

    async def do_create(self, obj_in: AppointmentListCreate):
        await self.create(obj_in=obj_in)
        return True

    async def do_delete(self, data_id: int):
        await self.remove(id=data_id)
        return True

    async def do_update(self, obj_in: AppointmentListUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        return True

    async def do_list(self, page: int, page_size: int, search: Q = Q(), order_by: str = "-id"):
        query = self.model.filter(search)
        total = await query.count()
        objs = await query.offset((page - 1) * page_size).limit(page_size).order_by(order_by)
        data = [await obj.to_dict() for obj in objs]
        return total, data

    async def do_total(self, space_id: int):
        now = datetime.now()
        # 今天的开始时间（00:00:00）
        start_of_today = now.replace(hour=0, minute=0, second=0, microsecond=0)
        # 明天的开始时间（00:00:00）
        start_of_tomorrow = start_of_today + timedelta(days=1)
        subquery = await self.model.filter(space_id=space_id, status=1, time__gte=start_of_today,
                                     time__lt=start_of_tomorrow).values_list('order_id', flat=True)
        total = await OrdersList.filter(id__in=subquery).count()

        return total

    async def do_detail(self, data_id: int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    async def do_refund(self, order_id: int):
        data = await AppointmentList.filter(order_id=order_id).first().values("id")
        if data:
            await self.do_delete(data["id"])

    async def do_success(self, order_id: int):
        await AppointmentList.filter(order_id=order_id).update(status=1)


appointment_list_controller = AppointmentListController()
